package dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.fragment_bill;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.R;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.activity_tally.HomeActivity;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.adapter.ClassifyAdapter;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.database.AccountDao;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.database.DatabaseHelper;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.entity.AccountBean;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.entity.ClassifyBean;



public class ClassifyFragment extends Fragment {

    private Button pieChartBtn_expenditure;
    private Button pieChartBtn_income;

    private String phoneNumber;
    private String date;

    ImageButton btn_leftArrow;
    ImageButton btn_rightArrow;
    TextView textView_month;
    PieChart pieChart;
    ArrayList<PieEntry> yValues = new ArrayList<>();
    ArrayList<String> xValues = new ArrayList<>();
    ArrayList<Integer> colors;


    int year,month;
    SimpleDateFormat sdf;
    int type;
    List<AccountBean> list;

    private ArrayList<ClassifyBean> msgList;
    private ClassifyAdapter mAdapter;
    ListView listView;
    ImageButton back;


    AccountDao dbManager;

    public ClassifyFragment(){}
    public ClassifyFragment(String phoneNumber){
        this.phoneNumber = phoneNumber;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_classify,null);
        pieChartBtn_expenditure = view.findViewById(R.id.pieChartBtn_expenditure);
        pieChartBtn_income = view.findViewById(R.id.pieChartBtn_income);
        btn_leftArrow = view.findViewById(R.id.btn_leftArrow);
        btn_rightArrow = view.findViewById(R.id.btn_rightArrow);
        back = view.findViewById(R.id.classify_back);
        textView_month = view.findViewById(R.id.textView_month);
        pieChart = view.findViewById(R.id.pieChart_classify);
        listView = view.findViewById(R.id.listView_classify);
        type = 1;
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });

        msgList = new ArrayList<>();
        list = new ArrayList<>();
        mAdapter = new ClassifyAdapter(msgList,this.getContext());
        listView.setAdapter(mAdapter);

        sdf = new SimpleDateFormat("yyyy.MM");
        String date = sdf.format(new Date());
        textView_month.setText(date);
        year = Integer.parseInt(date.substring(0,4));
        month = Integer.parseInt(date.substring(5,7));
        //点击左键头，处理年月显示，处理数据的更改
        btn_leftArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                month = month-1;
                if(month == 0){
                    month = 12;
                    year = year-1;
                }
                Calendar c = Calendar.getInstance();
                c.set(Calendar.MONTH,month-1);
                c.set(Calendar.YEAR,year);
                textView_month.setText(sdf.format(c.getTime()));

                xValues.clear();
                yValues.clear();
                msgList.clear();
                getData();
                mAdapter.notifyDataSetChanged();
            }
        });
        //点击右键头，处理年月显示，处理数据的更改
        btn_rightArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                month = month+1;
                if(month == 13){
                    month = 1;
                    year = year+1;
                }
                Calendar c = Calendar.getInstance();
                c.set(Calendar.MONTH,month-1);
                c.set(Calendar.YEAR,year);
                textView_month.setText(sdf.format(c.getTime()));

                xValues.clear();
                yValues.clear();
                msgList.clear();
                getData();
                mAdapter.notifyDataSetChanged();
            }
        });
        //点击支出按钮，显示支出
        pieChartBtn_expenditure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type=1; //0表示收入，1表示支出

                xValues.clear();
                yValues.clear();
                msgList.clear();
                pieChart.setCenterText("支出");
                getData();
                mAdapter.notifyDataSetChanged();
            }
        });
        //点击收入按钮，收入支出
        pieChartBtn_income.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type=0;//0表示收入，1表示支出

                xValues.clear();
                yValues.clear();
                msgList.clear();
                pieChart.setCenterText("收入");
                getData();
                mAdapter.notifyDataSetChanged();
            }
        });
        dbManager = new AccountDao(getContext(),phoneNumber);
        initColors();
        pieChart.setCenterText("支出");
        getData();
        return view;
    }
    private void getData(){
        if(type==1){
            //获取所选择月份的支出统计结果
            list = dbManager.getExpenditureStatisticsList(textView_month.getText().toString());
        }
        else{
            //获取所选择月份的收入统计结果
            list = dbManager.getIncomeStatisticsList(textView_month.getText().toString());
        }
        //将得到的数据导入饼图控件
        for(int i = 0; i < list.size(); i++){
            xValues.add(list.get(i).getCategory());
            yValues.add(new PieEntry((float)list.get(i).getAccount(),list.get(i).getCategory()));
        }
        setPieChart();
        //将得到的数据导入列表控件
        setListView();
    }
    private void setPieChart(){
        //y轴的集合
        PieDataSet pieDataset=new PieDataSet(yValues,"");

        pieDataset.setSliceSpace(2f);//设置各个饼图之间的距离
        pieDataset.setColors(colors);//设置颜色
        //禁用
        pieDataset.setDrawValues(false);
        pieDataset.setDrawIcons(false);
        Description description = pieChart.getDescription();
        description.setEnabled(false);

        PieData pieData=new PieData(pieDataset);
        pieChart.setData(pieData);

        pieChart.setUsePercentValues(true);//显示百分比
        pieChart.setExtraOffsets(5,10,5,5);//设置偏移量
        pieChart.setDrawHoleEnabled(true);//是否内环显示
        pieChart.setTransparentCircleRadius(55f);//空心圆半径
        pieChart.setHoleRadius(50f);//内环半径
        pieChart.setDrawCenterText(true);//饼状图中间可以添加文字
        pieChart.setRotationAngle(90);//初始旋转角度
        pieChart.setCenterTextSize(24);//设置中间文字大小
        pieChart.setDrawEntryLabels(false);//饼状图不显示label
        //设置图例
        Legend mLegend=pieChart.getLegend();  //设置比例图
        mLegend.setForm(Legend.LegendForm.SQUARE);  //设置比例图的形状，默认是方形
        mLegend.setXEntrySpace(7f);
        mLegend.setYEntrySpace(5f);
        mLegend.setEnabled(true);  //显示比例图即显示小方块
        mLegend.setOrientation(Legend.LegendOrientation.VERTICAL);//纵向
        pieChart.invalidate();
    }

    private void initColors(){
        colors=new ArrayList<Integer>();
        colors.add(Color.parseColor("#FFC90E"));
        colors.add(Color.parseColor("#22B14C"));
        colors.add(Color.parseColor("#FFAEC9"));
        colors.add(Color.parseColor("#99D9EA"));
        colors.add(Color.parseColor("#7092BE"));
        colors.add(Color.parseColor("#00A2E8"));
        colors.add(Color.parseColor("#A349A4"));
    }
    private void setListView(){
        //msgList中保存着统计得出的各类的名称、占比和总额
        ClassifyBean classifyBean = new ClassifyBean("类型","占比","金额");
        msgList.add(classifyBean);
        //设置金额输出格式
        NumberFormat nf = java.text.NumberFormat.getPercentInstance();
        nf.setMaximumIntegerDigits(3);//小数点前保留3位
        nf.setMinimumFractionDigits(2);// 小数点后保留2位

        PieData pieData = pieChart.getData();
        PieDataSet pieDataSet = (PieDataSet) pieData.getDataSet();
        float sum = pieData.getYValueSum();//计算占比之前所需的总额
        for(int i = 0; i < pieDataSet.getEntryCount(); i++){
            PieEntry pieEntry = pieDataSet.getEntryForIndex(i);
            classifyBean = new ClassifyBean(xValues.get(i),nf.format(pieEntry.getValue()/sum),
                    new DecimalFormat("0.00").format(pieEntry.getValue()));
            msgList.add(classifyBean);
        }
    }

}